package com.giacom.docx4j.plugin.impl;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class DDLGenerator {

	//static final String[] classes = { "Pessoa" };

	public static void main(String[] args) throws ClassNotFoundException {
		DDLGenerator gen = new DDLGenerator();
		gen.generate("SQLSERVER;ORACLE", new String[]{ "Pessoa" });
	}

	public String generate(String dialectString, String[] classes) throws ClassNotFoundException {

		String[] dials = dialectString.split(";");
		for (String di : dials) {
			DialectEnum dialect = DialectEnum.getDialect(di);
			
			Configuration cfg = new Configuration();

			for (int i = 0; i < classes.length; i++) {
				cfg.addAnnotatedClass(Class.forName(classes[i]));
			}

			cfg.setProperty("hibernate.dialect", dialect.getDialectClass());
			cfg.setProperty("format_sql","true");


			SchemaExport export = new SchemaExport(cfg);
			export.setDelimiter(";");

			String output = "./gen/" + classes[0] + "_" + dialect.name().toLowerCase() + "_ddl" + "_" + ".sql";

			export.setOutputFile(output);
			export.execute(true, false, false, false);
			
			return output;
		}
		return null;

	}

	/**
	 * Holds the classnames of hibernate dialects for easy reference.
	 */
	private static enum DialectEnum {
		ORACLE("org.hibernate.dialect.Oracle10gDialect"),
		PROGRESS("org.hibernate.dialect.ProgressDialect"),
		SQLSERVER("org.hibernate.dialect.SQLServerDialect"),
		DB2("org.hibernate.dialect.DB2Dialect"),
		POSTGRESQL("org.hibernate.dialect.PostgreSQLDialect"),
		MYSQL("org.hibernate.dialect.MySQLDialect");
		

		private String dialectClass;

		private DialectEnum(String dialectClass) {
			this.dialectClass = dialectClass;
		}

		public String getDialectClass() {
			return dialectClass;
		}
		
		protected static DialectEnum getDialect(String dialect){
			for (DialectEnum dialectEnum : DialectEnum.values()) {
				if(dialect.equals(dialectEnum.name())){
					return dialectEnum;
				}
			}
			
			return null;
		}
		
	}

}
